/*
* This is to implement the main test fuction.
*/
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include "memory.h"
#include "start_memory.h"
#include "get_memory.h"
#include "release_memory.h"
#include "grow_memory.h"
#include "pregrow_memory.h"
#include "end_memory.h"

extern int info[MAX_L];
extern int sum;
extern Buddy* p_tree;
extern void* base;
extern sem_t g_sem;


void
process1(void) {

    int size = 100;

    void *p = get_memory(size);
    p = grow_memory(p, size+20);

    p = pregrow_memory(p, size+30);

    release_memory(p);

}

void
process2(void) {

    int size = 200;

    void *p = get_memory(size);
    p = grow_memory(p, size+10);

    //release_memory(p);

}

int
main (int argc, char **argv) {
  int return_value = 0;

  if(start_memory(2048))
    printf("malloc successful!\n");
  else {
	printf("malloc fails :( \n");
  } 

  sem_init(&g_sem,0, SEM_FREE);
  
    int i;
	pthread_t proc1;
	pthread_t proc2;
	pthread_t proc3;
	if (pthread_create(&proc1, NULL, (void *)process1, NULL) != 0)
			printf("fail to create thread.\n");
	if (pthread_create(&proc2, NULL, (void *)process2, NULL) != 0)
			printf("fail to create thread.\n");
	if (pthread_create(&proc3, NULL, (void *)process1, NULL) != 0)
			printf("fail to create thread.\n");
  
  
  
  
  
  void* p1 = get_memory(4);
  void* p2 = get_memory(4);
  //void* p3 = get_memory(4);
  //void* p4 = get_memory(4);
  
  //release_memory(p1);
  grow_memory(p2,20);
  //grow_memory(p1,24);*/
  
  
  /*
  //grow_memory test case#1 -----------problem  size can't fit in original place, can't grow in same block of memory
  void* p2;
  printf("The address before grow is %p\n", p2);
  void* p1 = get_memory(4);
   p2 = get_memory(4);
  grow_memory(p2,40);
  printf("The address after grow is %p\n", p2);
  */
  
  /*
  //grow_memory test case#2 -----------problem  size can't fit in original place, but can grow in same block of memory
  void* p1 = get_memory(4);
  void* p2 = get_memory(4);
  void* p3 = get_memory(4);
  release_memory(p2);
  printf("The address before grow is %p\n", p3);
  grow_memory(p3,20);
  printf("The address after grow is %p\n", p3);
  */
  
  //grow_memory test case#3 size can fit in original place (new size< old size or new size< limit of the node)  pass
  /*void* p1 = get_memory(4);
  void* p2 = get_memory(4);
  void* p3 = get_memory(4);
  void* p4 = get_memory(4);
  pregrow_memory(p2,4);
  pregrow_memory(p3,3);
  */
  
  /*
  //grow_memory test case#4 can't fit in any memory partition thus can't grow  pass
  void* p1 = get_memory(100);
  grow_memory(p1, 130);
  */
  
  
  end_memory();
  
  return return_value;
}




